//
//  PKRequestManager.m
//  PianKe
//
//  Created by ybq on 15/12/22.
//  Copyright © 2015年 B7_Young. All rights reserved.
//

#import "PKRequestManager.h"

@implementation PKRequestManager

+ (void)requestWithUrlString:(NSString *)urlString parDic:(NSDictionary *)parDic Method:(RequestType)method finish:(Finish)finish error:(Error)error {
    NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    if (method == POST) {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0) {
            NSMutableArray *strArray = [NSMutableArray array];
            for (NSString *key in parDic) {
                NSString *str = [NSString stringWithFormat:@"%@=%@", key, parDic[key]];
                [strArray addObject:str];
            }
            // 拼接数组里的元素
            NSString *parString = [strArray componentsJoinedByString:@"&"];
            [request setHTTPBody:[parString dataUsingEncoding:NSUTF8StringEncoding]];
        }
    }
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue currentQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        if (connectionError == nil) {
            // 请求成功
            finish(data);   // 函数的调用
        } else {
            // 请求失败
            error(connectionError);    // 函数的调用
        }
    }];
}

@end
